package com.frog.queue.starter.sqs.container;

import com.frog.queue.starter.sqs.listener.ApplicationReadyListener;
import org.springframework.context.SmartLifecycle;

/**
 * @author wuqiong 2022/4/11
 * @description
 */
public abstract class AbstractMessageListenerContainer implements SmartLifecycle {
    protected boolean isRunning = false;
    protected Long sleepTimeMilliSeconds = 1000L;

    protected abstract void doStart();
    protected abstract void doInit();

    @Override
    public void start() {
        setRunning(true);
        new Thread(() -> {
            doInit();
            while (!ApplicationReadyListener.START_LISTENER_CONTAINER.get()) sleep(sleepTimeMilliSeconds);
            while (isRunning() && !Thread.currentThread().isInterrupted()) doStart();
        }).start();
    }

    @Override
    public void stop() {
        setRunning(false);
    }

    @Override
    public void stop(Runnable callback) {
        callback.run();
        setRunning(false);
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }

    protected void setRunning(boolean bool){
        isRunning = bool;
    }

    protected void sleep(long sleepTimeMilliSeconds) {
        try {
            Thread.sleep(sleepTimeMilliSeconds * 5L);
        } catch (InterruptedException e) {
        }
    }


}
